<template>
  <div class="user-list-container">
    <a-card class="main-card">
      <template #title>
        <div class="card-title">
          <span>人员管理</span>
        </div>
      </template>

      <!-- 操作按钮区域 -->
      <div class="action-header">
        <template v-if="storeMsg.storeId === '66a0788d4'">
          <a-select
            v-model:value="selectedStoreId"
            style="width: 200px; margin-right: 16px"
            placeholder="请选择门店"
            @change="handleStoreChange"
          >
            <a-select-option v-for="store in storeList" :key="store.storeId" :value="store.storeId">
              {{ store.storeName }}
            </a-select-option>
          </a-select>
        </template>
        <a-button type="primary" @click="showAddModal">
          添加人员
        </a-button>
      </div>

      <!-- 用户列表 -->
      <a-table
        :columns="columns"
        :data-source="userList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="userId"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'avatar'">
            <a-avatar
              :src="record.avatar"
              :size="40"
            >
              {{ record.avatar ? '' : record.userName?.charAt(0) }}
            </a-avatar>
          </template>
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 1 ? 'success' : 'error'">
              {{ record.status === 1 ? '正常' : '禁用' }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleEdit(record)">编辑</a-button>
              <a-popconfirm
                title="确定要删除该人员吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record)"
              >
                <a-button type="link" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加人员弹窗 -->
    <a-modal
      v-model:visible="addModalVisible"
      title="添加人员"
      @ok="handleAddSubmit"
      @cancel="handleAddCancel"
      :confirmLoading="addLoading"
    >
      <a-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        layout="vertical"
      >
        <a-form-item label="手机号" name="phone">
          <a-input-search
            v-model:value="addForm.phone"
            placeholder="请输入手机号"
            :loading="searchLoading"
            @search="handleSearchUser"
            allowClear
          >
            <template #enterButton>
              <a-button type="primary">搜索</a-button>
            </template>
          </a-input-search>
          <a-select
            v-if="searchResult"
            v-model:value="selectedUser"
            style="width: 100%; margin-top: 8px"
            placeholder="请选择用户"
            @change="handleUserSelect"
          >
            <a-select-option :value="searchResult.username">
              <div style="display: flex; align-items: center; gap: 8px">
                <a-avatar :size="24" :src="searchResult.avatar">
                  {{ searchResult.avatar ? '' : searchResult.username?.charAt(0) }}
                </a-avatar>
                <span>{{ searchResult.username }}</span>
              </div>
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="角色" name="roleId">
          <a-select
            v-model:value="addForm.roleId"
            placeholder="请选择角色"
            :loading="roleLoading"
          >
            <a-select-option v-for="role in roleList" :key="role.roleId" :value="role.roleId">
              {{ role.roleName }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑人员弹窗 -->
    <a-modal
      v-model:visible="editModalVisible"
      title="编辑人员"
      @ok="handleEditSubmit"
      @cancel="handleEditCancel"
      :confirmLoading="editLoading"
    >
      <a-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        layout="vertical"
      >
        <a-form-item label="用户名">
          <div style="display: flex; align-items: center; gap: 8px">
            <a-avatar :size="32" :src="editForm.avatar">
              {{ editForm.avatar ? '' : editForm.userName?.charAt(0) }}
            </a-avatar>
            <span>{{ editForm.userName }}</span>
          </div>
        </a-form-item>
        <a-form-item label="手机号">
          <span>{{ editForm.phone }}</span>
        </a-form-item>
        <a-form-item label="角色" name="roleId">
          <a-select
            v-model:value="editForm.roleId"
            placeholder="请选择角色"
            :loading="roleLoading"
          >
            <a-select-option v-for="role in roleList" :key="role.roleId" :value="role.roleId">
              {{ role.roleName }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { getStoreUser, search, bindRole, delUserRole } from '@/api/user';
import { listRole } from '@/api/role';
import { useStoreMsgStore } from '@/store/useStoreMsgStore';
import { listAllStores } from '@/api/store';
import type { TablePaginationConfig } from 'ant-design-vue';
import type { FormInstance } from 'ant-design-vue';

interface User {
  userId: string;
  phone: string;
  userName: string;
  avatar: string;
  status: number;
  createTime: string;
  updateTime: string;
  roleId: number;
  roleName: string;
  sort: number;
}

interface Role {
  roleId: number;
  roleName: string;
}

// 获取当前门店信息
const storeMsg = useStoreMsgStore();

// 当前页面选择的门店ID
const currentStoreId = ref(storeMsg.storeId);

// 用户列表数据
const userList = ref<User[]>([]);
const loading = ref(false);

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条记录`
});

// 表格列定义
const columns = [
  {
    title: '头像',
    dataIndex: 'avatar',
    key: 'avatar',
    width: 80
  },
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName',
    width: 120
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
    width: 120
  },
  {
    title: '角色',
    dataIndex: 'roleName',
    key: 'roleName',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
];

// 加载用户列表
const loadUserList = async () => {
  if (!currentStoreId.value) return;
  
  loading.value = true;
  try {
    const res = await getStoreUser(
      currentStoreId.value,
      pagination.current,
      pagination.pageSize
    );
    
    if (res.data.code === 200) {
      userList.value = res.data.data.list;
      pagination.total = res.data.data.total;
    } else {
      message.error(res.data.msg || '获取用户列表失败');
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
    message.error('获取用户列表失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 处理表格变化（分页）
const handleTableChange = (pag: TablePaginationConfig) => {
  pagination.current = pag.current || 1;
  pagination.pageSize = pag.pageSize || 10;
  loadUserList();
};

// 编辑相关数据
const editModalVisible = ref(false);
const editLoading = ref(false);
const editFormRef = ref<FormInstance>();
const editForm = reactive({
  userId: '',
  userName: '',
  phone: '',
  avatar: '',
  roleId: undefined as number | undefined
});

// 编辑表单验证规则
const editFormRules = {
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
};

// 处理编辑
const handleEdit = (record: User) => {
  editForm.userId = record.userId;
  editForm.userName = record.userName;
  editForm.phone = record.phone;
  editForm.avatar = record.avatar;
  editForm.roleId = record.roleId;
  editModalVisible.value = true;
  loadRoleList();
};

// 提交编辑
const handleEditSubmit = () => {
  editFormRef.value?.validate().then(async () => {
    if (!currentStoreId.value) {
      message.warning('请先选择门店');
      return;
    }

    if (!editForm.roleId) {
      message.warning('请选择角色');
      return;
    }

    editLoading.value = true;
    try {
      const res = await bindRole({
        storeId: currentStoreId.value,
        userId: editForm.userId,
        roleId: editForm.roleId
      });

      if (res.data.code === 200) {
        message.success('修改成功');
        editModalVisible.value = false;
        loadUserList();
      } else {
        message.error(res.data.msg || '修改失败');
      }
    } catch (error) {
      console.error('修改用户失败:', error);
      message.error('修改失败，请稍后重试');
    } finally {
      editLoading.value = false;
    }
  });
};

// 取消编辑
const handleEditCancel = () => {
  editFormRef.value?.resetFields();
  editModalVisible.value = false;
};

// 添加人员相关数据
const addModalVisible = ref(false);
const addLoading = ref(false);
const searchLoading = ref(false);
const roleLoading = ref(false);
const addFormRef = ref<FormInstance>();
const addForm = reactive({
  phone: '',
  userName: '',
  roleId: undefined as number | undefined
});

// 角色列表
const roleList = ref<Role[]>([]);

// 加载角色列表
const loadRoleList = async () => {
  roleLoading.value = true;
  try {
    const res = await listRole(1, 20, '');
    if (res.data.code === 200) {
      roleList.value = res.data.data.list.map((item: any) => ({
        roleId: item.id,
        roleName: item.roleName
      }));
    } else {
      message.error(res.data.msg || '获取角色列表失败');
    }
  } catch (error) {
    console.error('获取角色列表失败:', error);
    message.error('获取角色列表失败，请稍后重试');
  } finally {
    roleLoading.value = false;
  }
};

// 添加表单验证规则
const addFormRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  userName: [
    { required: true, message: '请选择用户', trigger: 'change' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
};

// 显示添加弹窗
const showAddModal = () => {
  addModalVisible.value = true;
  loadRoleList();
};

// 搜索结果
const searchResult = ref<{
  username: string;
  avatar: string;
  userId: string;
} | null>(null);

// 选中的用户
const selectedUser = ref<string>('');

// 搜索用户
const handleSearchUser = async (value: string) => {
  if (!value) {
    message.warning('请输入手机号');
    return;
  }
  
  searchLoading.value = true;
  try {
    const res = await search(value);
    if (res.data.code === 200) {
      if (res.data.data) {
        searchResult.value = {
          ...res.data.data,
          userId: res.data.data.userId
        };
        message.success('用户查找成功');
      } else {
        message.warning('未找到该用户');
        searchResult.value = null;
      }
    } else {
      message.error(res.data.msg || '搜索用户失败');
      searchResult.value = null;
    }
  } catch (error) {
    console.error('搜索用户失败:', error);
    message.error('搜索用户失败，请稍后重试');
    searchResult.value = null;
  } finally {
    searchLoading.value = false;
  }
};

// 处理用户选择
const handleUserSelect = (value: string) => {
  if (searchResult.value) {
    addForm.userName = value;
  }
};

// 提交添加
const handleAddSubmit = () => {
  addFormRef.value?.validate().then(async () => {
    if (!currentStoreId.value) {
      message.warning('请先选择门店');
      return;
    }

    if (!addForm.roleId) {
      message.warning('请选择角色');
      return;
    }

    if (!searchResult.value?.userId) {
      message.warning('请先搜索并选择用户');
      return;
    }

    addLoading.value = true;
    try {
      const res = await bindRole({
        storeId: currentStoreId.value,
        userId: searchResult.value.userId,
        roleId: addForm.roleId
      });

      if (res.data.code === 200) {
        message.success('添加成功');
        addModalVisible.value = false;
        loadUserList();
      } else {
        message.error(res.data.msg || '添加失败');
      }
    } catch (error) {
      console.error('添加用户失败:', error);
      message.error('添加失败，请稍后重试');
    } finally {
      addLoading.value = false;
    }
  });
};

// 取消添加
const handleAddCancel = () => {
  addFormRef.value?.resetFields();
  addModalVisible.value = false;
  searchResult.value = null;
  selectedUser.value = '';
};

// 处理删除
const handleDelete = async (record: User) => {
  if (!currentStoreId.value) {
    message.warning('请先选择门店');
    return;
  }

  try {
    const res = await delUserRole(currentStoreId.value, record.userId);

    if (res.data.code === 200) {
      message.success('删除成功');
      loadUserList();
    } else {
      message.error(res.data.msg || '删除失败');
    }
  } catch (error) {
    console.error('删除用户失败:', error);
    message.error('删除失败，请稍后重试');
  }
};

// 门店列表
const storeList = ref<Array<{
  storeId: string;
  storeName: string;
}>>([]);

// 选中的门店ID
const selectedStoreId = ref<string>('');

// 加载门店列表
const loadStoreList = async () => {
  try {
    const res = await listAllStores();
    if (res.data.code === 200) {
      storeList.value = res.data.data.map((store: any) => ({
        storeId: store.storeId,
        storeName: store.storeName
      }));
    } else {
      message.error(res.data.msg || '获取门店列表失败');
    }
  } catch (error) {
    console.error('获取门店列表失败:', error);
    message.error('获取门店列表失败，请稍后重试');
  }
};

// 处理门店选择变化
const handleStoreChange = (value: string) => {
  selectedStoreId.value = value;
  currentStoreId.value = value;
  loadUserList();
};

// 页面加载时获取用户列表和门店列表
onMounted(() => {
  loadUserList();
  if (storeMsg.storeId === '66a0788d4') {
    loadStoreList();
  }
});
</script>

<style scoped>
.user-list-container {
  padding: 24px;
}

.main-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.card-title {
  font-size: 18px;
  font-weight: 500;
  color: #1f1f1f;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 500;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #f5f5f5;
}

:deep(.ant-btn-link) {
  padding: 4px 8px;
}

:deep(.ant-tag) {
  margin: 0;
}

.action-header {
  margin-bottom: 24px;
}

:deep(.ant-input-search) {
  width: 100%;
}

:deep(.ant-select) {
  width: 100%;
}

:deep(.ant-avatar) {
  background-color: #f0f2f5;
  color: #666;
  font-size: 14px;
}
</style> 